﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using IHISCETeim.Model;
using IHISCETeim.BLL;
using IHISCETeim.Library;
using FineUI;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Data;

namespace IHISCETeim.Web.AgentSys.SvrMgr
{
    public partial class AgentQltySvrMgrEdit : AgentPageBase
    {

        protected override Permission[] PowerKey
        {
            get
            {
                return new Permission[] { Permission.修改 };
            }
        }
        protected override string DWZRef
        {
            get { return "AgentQltySvrMgrList"; }
        }

        protected int QltyId
        {
            get
            {
                return GetRequestValue<int>("QltyId", 0);
            }
        }
        private AgentQltyInfo _objQlty = null;
        protected AgentQltyInfo objQlty
        {
            get
            {
                if (_objQlty == null)
                {
                    _objQlty = AgentQltyController.GetByQltyId(QltyId);
                }
                return _objQlty;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadData();
            }
        }
        private void LoadData()
        {
            btnClose.OnClientClick = GetCloseActiveTabScript(); ;
            //如果 此品情单状态 不是 服务经理审核中 ,则不能进行审核处理.
            if (objQlty.ClaimState == IHISCETeim.Web.ClaimState.服务经理审核中.ToString() || objQlty.ClaimState == IHISCETeim.Web.ClaimState.服务部长审核中.ToString())
            {
                if (objQlty.SrvMangerUserId != base.User.UserId)
                {
                    Alert.Show("您无权审核此品情,此品情审核人员为" + OUserController.GetById(objQlty.SrvMangerUserId).RealName);
                    this.btnReject.Hidden = true;
                    this.btnSaveClose.Hidden = true;
                }
                //上级可审核下级的品情
               if(AgentConfigController.GetByUserId(objQlty.SrvMangerUserId).ParId==base.User.UserId)
                {
                    
                }
            }
            else {
                Alert.Show("此品情不需要审核(或已审核过)");
                this.btnReject.Hidden = true;
                this.btnSaveClose.Hidden = true;
                
            }
            LoadQltyInfo();
        }

        private void LoadQltyInfo()
        {
            this.ClaimsNumber.Text = objQlty.ClaimsNumber;
            this.IssueDate.Text = objQlty.IssueDate.ToString("yyyy-MM-dd");
            this.AgentName.Text = objQlty.AgentName;
            this.SerialNumber.Text = objQlty.SerialNumber;
            this.MachineType.Text = objQlty.MachineType;
            this.CustomerName.Text = objQlty.CustomerName;
            this.CustomerMobile.Text = objQlty.CustomerMobile;
            this.IntoDate.Text = objQlty.IntoDate == DateTime.MinValue ? "" : objQlty.IntoDate.ToString("yyyy-MM-dd");
            this.IntoAddress.Text = objQlty.IntoAddress;
            this.FaultDate.Text = objQlty.FaultDate.ToString("yyyy-MM-dd");
            this.WorkHour.Text = objQlty.WorkHour.ToString("F0");
            this.ReportUser.Text = objQlty.ReportUser;
            this.ReportTel.Text = objQlty.ReportTel;
            this.MacNature.SelectedValue = objQlty.MacNature;
            this.IntoConditi.SelectedValue = objQlty.IntoConditi;
            this.IntoSpecial.SelectedValue = objQlty.IntoSpecial;
            this.DamagePartsNumber.Text = objQlty.DamagePartsNumber;
            this.HEFaultDescription.Text = objQlty.FaultDescription;
            //this.MainFault.SelectedValue = objQlty.MainFault;
            this.HEFaultReason.Text = objQlty.FaultReason;
            this.HEProcessMode.Text = objQlty.ProcessMode;
            this.PartsAcceptAddress.Text = objQlty.PartsAcceptAddress;
            this.PartsAcceptName.Text = objQlty.PartsAcceptName;
            this.PartsAcceptTel.Text = objQlty.PartsAcceptTel;
            this.PartsAcceptDate.SelectedValue = objQlty.PartsAcceptDate;

            this.ReportType.SelectedValue = objQlty.ReportType;
            this.IsVisit.Checked = objQlty.IsVisit;
            this.SvrResult.Text = objQlty.SvrResult;
            this.SvrScheme.Text = objQlty.SvrScheme;
            this.PartsSendDate.SelectedValue = objQlty.PartsSendDate;
            this.PartsSendType.SelectedValue = objQlty.PartsSendType;


            this.ClaimState.Text = objQlty.ClaimState;
           // this.CancelReason.Text = objQlty.CancelReason;
           // this.IsCancelReason.Checked = objQlty.IsCancelReason;
            //this.CancelReason.Readonly = objQlty.IsCancelReason;
           // this.RejectReason.Text = objQlty.RejectReason;
            //this.RejectReason.Visible = !string.IsNullOrEmpty(objQlty.RejectReason);

            ///加载图片
            List<AgentQltyImgInfo> listImg = AgentQltyController.GetAllImgByQltyId_0(QltyId);
            for (int imgIndex = 1; imgIndex <= listImg.Count-1; imgIndex++)
            {
                //FineUI.FileUpload FileUpladControl = Panel4.FindControl("filePhoto" + imgIndex) as FineUI.FileUpload;                
                FineUI.Image imgRelativelyControl = Panel4.FindControl("imgRelatively" + imgIndex) as FineUI.Image;
                FineUI.TextBox ImgTitleControl = Panel4.FindControl("ImgTitle" + imgIndex) as FineUI.TextBox;

                ImgTitleControl.Text = listImg[imgIndex - 1].Title;
                imgRelativelyControl.ImageUrl = listImg[imgIndex - 1].IMGRelatively;
            }
            try
            {
                //this.fileOther.Label = listImg[6].IMGRelatively;
                this.fileOtherDownLoad.NavigateUrl = listImg[6].IMGRelatively; ;
                //this.fileOtherDownLoad.Hidden = string.IsNullOrEmpty(listImg[6].IMGRelatively);
            }
            catch { }

            //加载配件
            List<AgentQltyPartsInfo> listParts = AgentQltyController.GetAllPartsByQltyId(QltyId);
            if (listParts.Count < 20)
            {
                int addNum = 20 - listParts.Count;
                while (addNum > 0)
                {
                    listParts.Add(new AgentQltyPartsInfo());
                    addNum = addNum - 1;
                }
            }
            this.grdAgentQltyParts.DataSource = listParts;
            this.grdAgentQltyParts.DataBind();

        }
        protected void filePhoto1_FileSelected(object sender, EventArgs e)
        {
            FineUI.FileUpload FileUpladControl = sender as FineUI.FileUpload;
            string cIndex = FileUpladControl.EmptyText;
            FineUI.Image imgRelativelyControl = Panel4.FindControl("imgRelatively" + cIndex) as FineUI.Image;



            if (FileUpladControl.HasFile)
            {
                string fileName = FileUpladControl.ShortFileName;

                if (!ValidateFileType(fileName))
                {
                    Alert.Show("无效的文件类型！");
                    return;
                }


                fileName = fileName.Replace(":", "_").Replace(" ", "_").Replace("\\", "_").Replace("/", "_");
                fileName = DateTime.Now.Ticks.ToString() + "_" + fileName;

                string path = GetUpLoadFilePath(User.Department);
                FileUpladControl.SaveAs(Server.MapPath(path + fileName));

                imgRelativelyControl.ImageUrl = path + fileName;

                // 清空文件上传组件
                FileUpladControl.Reset();
            }
        }
        protected void fileOther_FileSelected(object sender, EventArgs e)
        {
            if (fileOther.HasFile)
            {
                string fileName = fileOther.ShortFileName;

                if (!ValidateFileType(fileName))
                {
                    Alert.Show("无效的文件类型！");
                    return;
                }


                fileName = fileName.Replace(":", "_").Replace(" ", "_").Replace("\\", "_").Replace("/", "_");
                fileName = DateTime.Now.Ticks.ToString() + "_" + fileName;

                string path = GetUpLoadFilePath(User.Department);
                fileOther.SaveAs(Server.MapPath(path + fileName));

                fileOtherDownLoad.Hidden = false;
                fileOtherDownLoad.NavigateUrl = path + fileName;
                fileOtherDownLoad.Text = fileName;

                // 清空文件上传组件
                fileOther.Reset();
            }
        }
        protected void grdAgentQltyParts_RowDataBound(object sender, GridRowEventArgs e)
        {
            AgentQltyPartsInfo itmData = e.DataItem as AgentQltyPartsInfo;
            System.Web.UI.WebControls.DropDownList ddl = grdAgentQltyParts.Rows[e.RowIndex].FindControl("ddlPartsDemand") as System.Web.UI.WebControls.DropDownList;
            ddl.SelectedValue = itmData.PartsDemand;

        }
        protected void grdAgentQltyParts_PreRowDataBound(object sender, GridPreRowEventArgs e)
        {
            AgentQltyPartsInfo itmData = e.DataItem as AgentQltyPartsInfo;
            // itmData.ItemCode
            if (!string.IsNullOrEmpty(itmData.ItemCode))
            {
                if (SBOController.GetHaveItemCode(itmData.ItemCode) == "")
                {
                    System.Web.UI.WebControls.TextBox tbItemCode = grdAgentQltyParts.Rows[e.RowIndex].FindControl("tbItemCode") as System.Web.UI.WebControls.TextBox;
                    tbItemCode.BackColor = System.Drawing.Color.Red;
                }
            }
        }

        protected void IsCancelReason_CheckedChanged(object sender, CheckedEventArgs e)
        {
            //this.CancelReason.Readonly = !this.IsCancelReason.Checked;
        }
        protected void DelteImage_Click(object sender, EventArgs e)
        {
            FineUI.LinkButton btnControl = sender as FineUI.LinkButton;
            string cIndex = btnControl.TabIndex.ToString();
            if (cIndex == "7")
            {
                fileOtherDownLoad.Text = "原文件下载";
                fileOtherDownLoad.NavigateUrl = "";
            }
            else
            {
                FineUI.Image imgRelativelyControl = Panel4.FindControl("imgRelatively" + cIndex) as FineUI.Image;
                imgRelativelyControl.ImageUrl = "/res/blank.png";
            }
        }
        /// <summary>
        /// 处理品情
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSaveClose_Click(object sender, EventArgs e)
        {           
            //通过审核
            SaveChange(true);
        }

        protected void btnReject_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.RejectReason.Text))
            {
                this.RejectReason.Focus();
                Alert.Show("请输入驳回原因.");
                return;
            }
            SaveChange(false);
        }

        private void SaveChange(bool pass)
        {
            AgentQltyInfo obj = objQlty;
            obj.QltyId = QltyId;
            obj.IssueDate = Convert.ToDateTime(this.IssueDate.Text);
            obj.SerialNumber = this.SerialNumber.Text;
            obj.MachineType = this.MachineType.Text;
            obj.CustomerName = this.CustomerName.Text;
            obj.AgentName = this.AgentName.Text;
            obj.CustomerMobile = this.CustomerMobile.Text;
            obj.IntoDate =string.IsNullOrEmpty(this.IntoDate.Text) ? DateTime.MinValue : Convert.ToDateTime(this.IntoDate.Text);
            obj.IntoAddress = this.IntoAddress.Text;
            obj.FaultDate = Convert.ToDateTime(this.FaultDate.Text);
            obj.WorkHour = Convert.ToDecimal(this.WorkHour.Text.Trim());
            obj.ReportUser = this.ReportUser.Text;
            obj.ReportTel = this.ReportTel.Text;
            obj.MacNature = this.MacNature.SelectedValue;
            obj.IntoConditi = this.IntoConditi.SelectedValue;
            obj.IntoSpecial = this.IntoSpecial.SelectedValue;
            obj.DamagePartsNumber = this.DamagePartsNumber.Text;
            obj.FaultDescription = StringHelper.StripTags(this.HEFaultDescription.Text, false);
            //obj.MainFaultID = Convert.ToInt32(this.MainFault.Text);
            obj.FaultReason = StringHelper.StripTags(this.HEFaultReason.Text, false);
            obj.ProcessMode = StringHelper.StripTags(this.HEProcessMode.Text, false);
            obj.PartsAcceptAddress = this.PartsAcceptAddress.Text;
            obj.PartsAcceptName = this.PartsAcceptName.Text;
            obj.PartsAcceptTel = this.PartsAcceptTel.Text;
            obj.PartsAcceptDate = this.PartsAcceptDate.SelectedValue;

            obj.ReportType = this.ReportType.SelectedValue;
            obj.IsVisit = this.IsVisit.Checked;
            obj.SvrResult = StringHelper.StripTags(this.SvrResult.Text, false);
            obj.SvrScheme = StringHelper.StripTags(this.SvrScheme.Text, false);
            obj.PartsSendDate = this.PartsSendDate.SelectedValue;
            obj.PartsSendType = this.PartsSendType.SelectedValue;

            //obj.SrvMangerUserId = AgentConfigController.SvrManagerUserId;
            //obj.ClaimState = ClaimState.担当确认中.ToString();
           // obj.RejectReason =pass?"": this.RejectReason.Text;//驳回原因
           // obj.IsCancelReason = this.IsCancelReason.Checked;
           // obj.CancelReason = this.IsCancelReason.Checked ? this.CancelReason.Text : "";

            //加载图片信息
            //AgentQltyImgInfo imgObj = new AgentQltyImgInfo();
            List<AgentQltyImgInfo> imgList = new List<AgentQltyImgInfo>();
            AgentQltyImgInfo imgObj = null;
            for (int imgIndex = 1; imgIndex <= 6; imgIndex++)
            {
                imgObj = new AgentQltyImgInfo();
                FineUI.Image imgRelativelyControl = Panel4.FindControl("imgRelatively" + imgIndex) as FineUI.Image;
                FineUI.TextBox ImgTitleControl = Panel4.FindControl("ImgTitle" + imgIndex) as FineUI.TextBox;
                imgObj.Title = ImgTitleControl.Text;
                imgObj.IMGRelatively = imgRelativelyControl.ImageUrl;
                imgObj.FileIndex = imgIndex;
                imgObj.FromType = 0;
                imgList.Add(imgObj);
            }
            imgObj = new AgentQltyImgInfo();
            imgObj.Title = "其它文件";
            imgObj.IMGRelatively = this.fileOtherDownLoad.NavigateUrl;
            imgObj.FileIndex = 7;
            imgObj.FromType = 0;
            imgList.Add(imgObj);
            //获取配件信息
            List<AgentQltyPartsInfo> partsList = new List<AgentQltyPartsInfo>();

            string checkitemcode = "";
            for (int i = 0, count = this.grdAgentQltyParts.Rows.Count; i < count; i++)
            {
                AgentQltyPartsInfo pobj = new AgentQltyPartsInfo();

                GridRow row = grdAgentQltyParts.Rows[i];
                System.Web.UI.WebControls.TextBox tbItemCode = (System.Web.UI.WebControls.TextBox)row.FindControl("tbItemCode");
                System.Web.UI.WebControls.TextBox tbDscription = (System.Web.UI.WebControls.TextBox)row.FindControl("tbDscription");
                FineUI.TextBox tbQuantity = (FineUI.TextBox)row.FindControl("Quantity");
                System.Web.UI.WebControls.DropDownList ddlPartsDemand = (System.Web.UI.WebControls.DropDownList)row.FindControl("ddlPartsDemand");
                FineUI.TextBox tbRemark = (FineUI.TextBox)row.FindControl("Remark");
                System.Web.UI.WebControls.CheckBox cbInStock = (System.Web.UI.WebControls.CheckBox)row.FindControl("InStock");
                if (!string.IsNullOrEmpty(tbItemCode.Text))
                {
                    if (SBOController.GetHaveItemCode(tbItemCode.Text.Trim()) == "")
                    {
                        checkitemcode += string.Format("<b>第{0}行</b>:【{1}】　{2}<br/>", i + 1, tbItemCode.Text.Trim(), tbDscription.Text.Trim());
                        continue;
                    }
                    pobj.ItemCode = tbItemCode.Text.Trim();
                    pobj.Dscription = tbDscription.Text.Trim();
                    pobj.Quantity = Convert.ToDecimal(tbQuantity.Text.Trim());
                    pobj.PartsDemand = ddlPartsDemand.SelectedValue;
                    pobj.LastPurPrice = Convert.ToDecimal(SBOController.GetOITMLastPurPrice(pobj.ItemCode));
                    pobj.Remark = tbRemark.Text;
                    pobj.InStock = cbInStock.Checked;
                    partsList.Add(pobj);
                }

            }
            if (!string.IsNullOrEmpty(checkitemcode))
            {
                Alert.Show("以下配件不存在ERP系统中,请重新确认:<br/>" + checkitemcode);
                return;
                //return -99;//表示有配件在ERP系统中不不存在
            }
            AgentQltyRejectInfo objReject = null;
            if (pass)
                objReject = null;
            else
            {
                objReject = new AgentQltyRejectInfo();
                objReject.RejectDate = DateTime.Now;
                objReject.RejectRealName = base.User.RealName;
                objReject.RejectReason = this.RejectReason.Text;
                objReject.FromType = 0;
                obj.RejectReason =  this.RejectReason.Text;//驳回原因
                
            }

            int reVal = AgentQltyController.SvrMgrEdit(pass, objReject, obj, imgList, partsList);
            switch (reVal)
            {
                case 0:
                    Alert.Show("品情处理失败,请通知IT部", "提示", MessageBoxIcon.Error);
                    break;
                case 1:
                    Alert.Show("品情已提交到上级审核.", "提示", MessageBoxIcon.Information, GetCloseReloadActiveTabScript());
                    break;
                case 2:
                    Alert.Show("品情已确认,系统已通知相应人员发货,请留意邮件通知.", "提示", MessageBoxIcon.Information, GetCloseReloadActiveTabScript());
                    break;
                case 3:
                    Alert.Show("品情已确认.", "提示", MessageBoxIcon.Information, GetCloseReloadActiveTabScript());
                    break;
                //case 4:
                //    Alert.ShowInParent("品情已取消,已邮件通知相关经销商内勤人员.", "提示", MessageBoxIcon.Information, GetCloseReloadActiveTabScript());
                //    //break;
                case 5:
                    Alert.Show("品情已驳回,系统已邮件通知相应的服务担当", "提示", MessageBoxIcon.Information, GetCloseReloadActiveTabScript());
                    break;
            }
        }
    }
}